# encoding = utf-8

'''
Author: Du
Blog：https://www.cnblogs.com/Du704/

Date: 2020/3/24 13:27
'''
import requests, glob, json, os, time
from concurrent.futures import ThreadPoolExecutor

data = {
    "id": None,
    "postType": 2,
    "title": "",
    "url": None,
    "postBody": '',
    "categoryIds": [1679067],
    "inSiteCandidate": False,
    "inSiteHome": False,
    "siteCategoryId": None,
    "blogTeamIds": None,
    "isPublished": True,
    "displayOnHomePage": False,
    "isAllowComments": True,
    "includeInMainSyndication": True,
    "isPinned": False,
    "isOnlyForRegisterUser": False,
    "isUpdateDateAdded": False,
    "entryName": None,
    "description": None,
    "tags": None,
    "password": None,
    "datePublished": "2020-03-24T09:36:59.827Z",
    "isMarkdown": True,
    "isDraft": True,
    "autoDesc": None,
    "changePostType": False,
    "blogId": 0,
    "author": None,
    "removeScript": False,
    "ip": None,
    "changeCreatedTime": False,
    "canChangeCreatedTime": False
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
    'Content-Type': 'application/json',
    'Cookie': '''_ga=GA1.2.1446121424.1571057707; __gads=ID=5307f922aeb64abd:T=1571057706:S=ALNI_MbxWcI7j4FCaZxzkU-IYn9nx8IGDA; .Cnblogs.AspNetCore.Cookies=CfDJ8Nf-Z6tqUPlNrwu2nvfTJEh8upQNcLTb0_n8aBdkLdZkDX7mxhSdX9E2o3CAPmWoIp2I7Qt0KhBFtOhIdfJiYZM19SQjJ3njxzQnFpbX3Yd5F_y_fY3tTydhfhI0k66s-5QSWKOXFmVQ8iXMnHbMelyeGjEqWE_T8vYLvEwqMfX1FHTo_D8LhdfgStGJ4xxrPeEcrBNhuOc0cRhIh44D6qiEcU3FBRWo9pYEsJZI92IyBspfKH_g8Ju_99cX0Q-K1DcME2-cfWgHplr55ur_84d_w0H_SPm2UjtQq26VUQ9cBwDjtwy_lAGpUGh015qa1BeDhY2HWX0wZ2QUoATiq94hrS12OYeMOFxjlQTxm44vN00xGNLnV5uOjqYEvTXYhnh-kwH_tHtjM1KptAISb5zLUIoE-343aAHR_rP3iqOPgGgGqQSiZ5LGFF77BLoUvcluZ1fRCejxliygXl-XS_ummL9dTYXI8GlD8SArvPk2ZEiKcnimEC0697J-nafxBM3rSAUss6zsK7qjziuLLCYO6f46S5NInrLLQq7pOAhcGYe4_GalbRjPbKc0GpdqPw; .CNBlogsCookie=6185A8EBD8B1FE4AA36E937F818B51926F0AD9D85D7B7B7EEDD8E2B9B06DB15B76035C7AA6B9F14A27ED023921275E4D30F9D3D3F546BB5DC174A8355EE7E49B4DF8AF168C3F98803D231D86D02829B92D6AA805; _gid=GA1.2.1169724486.1585040912; _gat_gtag_UA_48445196_1=1''',
    'origin': 'https://i-beta.cnblogs.com',
    'referer': 'https://i-beta.cnblogs.com/articles/edit',
    'x-blog-id': '529726',
}

import os

url = 'https://i-beta.cnblogs.com/api/posts'
upload_path = './upload_blogs/20200324/'
# for mdfile in glob.glob(upload_path + '*.md'):
#     title = os.path.basename(mdfile)
#     title, _ = os.path.splitext(title)
#     print(title)

lis = list()


def upload_blog(upload_path):
    post_data = data.copy()

    with open(upload_path, 'r', encoding='utf8') as f:
        postBody = f.read()

    title = os.path.basename(upload_path)
    title, _ = os.path.splitext(title)

    post_data['postBody'] = postBody
    post_data['title'] = title

    # print(f'正在上传 {title} ...')
    res = requests.post(url, data=json.dumps(post_data), headers=headers)
    if res.status_code == 200:
        res = res.json()
        lis.append({'id': res.get('id'), 'url': res.get('url')})
        print(f'{title} 上传成功')
        os.remove(upload_path)
        return {'id': res.get('id'), 'title': title, 'url': res.get('url')}

    else:
        print(f'{title}上传失败：', res.json())


def get_result(future):
    '''这个回调函数我还没想好怎么用'''
    # print(future.result)
    ...


if __name__ == '__main__':
    # with ThreadPoolExecutor(max_workers=4) as pool:
    #     for mdfile in glob.glob(upload_path + '*.md'):
    #         pool.submit(upload_blog, mdfile).add_done_callback(get_result)
    with open('upload_list.json', 'a', encoding='utf8') as f:

        for mdfile in glob.glob(upload_path + '*.md'):
            res = upload_blog(mdfile)
            if res:
                json.dump(res, f)

            time.sleep(66)
